﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace X10d.Interface.States
{
	/// <summary>
	/// Responds to a time request from the interface
	/// </summary>
	internal class HandleTimeUpdateRequest : PortStateBase
	{
		public override void HandleArrive(IRequestManager requestManager)
		{
			Log.Info("Time update request");

			DateTime now = DateTime.Now;
			byte[] buffer = new byte[7];
			buffer[0] = TimeUpdate;
			buffer[1] = (byte)now.Second;
			buffer[2] = (byte)(((now.Hour * 60) + now.Minute) % 120);
			buffer[3] = (byte)(now.Hour / 2);
			buffer[4] = (byte)now.DayOfYear;
			buffer[5] = (byte)now.DayOfYear;
			buffer[6] = (byte)HouseCodeType.B; // TODO: replace with default housecode

			Log.Info("Sending time response");
			Log.WriteBuffer(buffer);

			requestManager.Port.Write(buffer, 0, buffer.Length);

			requestManager.TransitionToState( new InterruptHandledState() );
		}

		/// <summary>
		/// Send the current time and date to the interface
		/// </summary>
		/// <param name="requestManager">
		/// Reference to the request manager
		/// </param>
		/// <param name="newBuffer">
		/// Buffer received from the interface
		/// </param>
		protected override void DoHandleNewBuffer(IRequestManager requestManager, byte[] newBuffer)
		{
			Log.Warning("Unexpected data encountered in time update request state");

			requestManager.TransitionToState( new ErrorState() );
		}
	}
}
